/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.compiler;

import com.aduib.boot.common.exception.CommonException;
import com.aduib.boot.common.util.ClassUtils;
import com.aduib.boot.common.util.IOUtils;
import com.aduib.boot.common.util.StrUtils;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;

import static com.aduib.boot.common.compiler.JavaPattern.CLASS_PATTERN;
import static com.aduib.boot.common.compiler.JavaPattern.PACKAGE_PATTERN;

/**
 * @description: AbstractCompiler
 * @author: zzh
 * @date: 2021/9/14 15:29
 */
public abstract class AbstractCompiler implements Compiler {

  @Override
  public Class<?> compile(String code, ClassLoader classLoader) {
    code = code.trim();
    Matcher matcher = PACKAGE_PATTERN.matcher(code);
    String pkg;
    if (matcher.find()) {
      pkg = matcher.group(1);
    } else {
      pkg = "";
    }
    matcher = CLASS_PATTERN.matcher(code);
    String cls;
    if (matcher.find()) {
      cls = matcher.group(1);
    } else {
      throw new IllegalArgumentException("No such class name in " + code);
    }
    String className = pkg != null && pkg.length() > 0 ? pkg + "." + cls : cls;
    try {
      return ClassUtils.forName(className, true, classLoader);
    } catch (ClassNotFoundException e) {
      if (!code.endsWith("}")) {
        throw new CommonException("The java code not endsWith \"}\", code: \n" + code + "\n");
      }
      try {
        return doCompile(className, code);
      } catch (RuntimeException t) {
        throw t;
      } catch (Throwable t) {
        throw new CommonException(
            "Failed to compile class, cause: "
                + t.getMessage()
                + ", class: "
                + className
                + ", code: \n"
                + code
                + "\n, stack: "
                + ClassUtils.stackTraceString(t));
      }
    }
  }

  @Override
  public Class<?> compile(byte[] code, ClassLoader classLoader) {
    return compile(StrUtils.str(code, StandardCharsets.UTF_8), classLoader);
  }

  @Override
  public Class<?> compile(InputStream inputStream, ClassLoader classLoader) {
    return compile(IOUtils.readBytes(inputStream), classLoader);
  }

  protected abstract Class<?> doCompile(String name, String source) throws Throwable;

  protected abstract Class<?> doCompile(byte[] code, String source) throws Throwable;

  protected abstract Class<?> doCompile(InputStream inputStream, String source) throws Throwable;
}
